package cn.yunhe.action;

import cn.yunhe.utils.BaseAction;
import lombok.Getter;
import lombok.Setter;
import org.apache.struts2.ServletActionContext;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class UpLoads extends BaseAction {
    @Getter
    @Setter
    private File[] uploads;
    @Getter
    @Setter
    private String[] uploadsFileName;
    @Getter
    @Setter
    private String[] uploadsContentType;
    @Setter
    private String savePath;

    public String getSavePath(){
        return ServletActionContext.getServletContext().getRealPath(savePath);
    }

    private void doUpload(File file,String uploadPath){
        try {
            FileOutputStream fos=new FileOutputStream(uploadPath);
            FileInputStream fis=new FileInputStream(file);
            byte[] b=new byte[1024];
            int len=0;
            while ((len=fis.read(b))!=-1){
                fos.write(b,0,len);
            }
            fis.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String execute() throws Exception {
        for (int i = 0; i < uploads.length; i++) {
            String uploadPath=getSavePath()+"\\"+uploadsFileName[i];
            doUpload(uploads[i],uploadPath);
        }
        return SUCCESS;
    }
}
